package com.zhome.gateway.filter.pre;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.enums.FilterEnum;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.enums.ZhomeHttpEnum;
import com.zhome.gateway.filter.AbstractZhomeZuulFilter;
import com.zhome.gateway.util.DesEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * 请求实体解密
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class RequestDecryptFilter extends AbstractZhomeZuulFilter {
    @Override
    public String filterType() {
        return Constants.PRE_KEY;
    }

    @Override
    public int filterOrder() {
        return FilterEnum.RequestDecryptFilterEnum.getFilterOrder();
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getBoolean(Constants.RequestContextKey.CTX_X_SUCCESSOR_CAN_EXECUTE);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String method = request.getMethod();
        if (ZhomeHttpEnum.isPostMethod(method)) {
            doPost(ctx, request);
        }
        return null;
    }

    public void doPost(RequestContext ctx, HttpServletRequest request) throws ZuulException {
        try {
            String requestBodyEncrpty = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
            String requestBody = DesEncrypt.decrypt(requestBodyEncrpty);
            ctx.set(Constants.RequestContextKey.CTX_X_REQUEST_BODY, requestBody);
        } catch (Exception e) {
            log.warn("RequestDecryptFilter Fail!RequestId:%s", requestId(), e);
            setFailResponse(GateWayCodeEnum.DECRYPT_FAIL);
        }
    }



}
